package com.nsi.service.Impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.nsi.async.AsyncTask;
import com.nsi.common.Const;
import com.nsi.util.RedisUtils;
import com.nsi.common.ResponseCode;
import com.nsi.common.ServerResponse;
import com.nsi.dao.LogMapper;
import com.nsi.dao.UserMapper;
import com.nsi.exception.NsiOperationException;
import com.nsi.pojo.Log;
import com.nsi.pojo.User;
import com.nsi.service.IUserService;
import com.nsi.util.Httpsrequest;
import com.nsi.util.MailUtil;
import com.nsi.util.PropertiesUtil;
import com.nsi.util.SmsUtil;
import com.old.model.Model;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Luo Zhen
 * @create 2018-08-21
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private SmsUtil smsUtil;
    @Autowired
    private AsyncTask asyncTask;

    private Gson gson = new Gson();

    @Override
    public void deleteByUserId(Integer userId) {
        userMapper.deleteByPrimaryKey(userId);
    }

    /**
     * 邮箱注册功能-旧方法
     */
    @Override
    public ServerResponse register(User user) {
        if (StringUtils.isBlank(user.getUserPortrait())) {
            user.setUserPortrait("0");
        }
        user.setMemberSign(3);
        user.setLoadTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        user.setUserScore(Const.NUM_DEFAULT_VALUE);
        user.setUserRegistercode(RandomStringUtils.randomNumeric(6));
        user.setRegisterType(Const.REGISTER_TYPE_SIKUQUANSHU);

        this.saveUser(user);
        //异步发送注册邮件
        asyncTask.sendRegisterCode(user.getUsername(), user.getUserRegistercode());

        return ServerResponse.createBySuccessMessage("注册成功-邮件发送成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public ServerResponse registerBySiKu(User user) {
        if (StringUtils.isEmpty(user.getUsername())) {
            throw new NsiOperationException("参数不合法！");
        }
        user.setMemberSign(3);
        user.setPassword("" + Const.NUM_DEFAULT_VALUE);
        user.setUserRegistercode("" + Const.NUM_DEFAULT_VALUE);
        user.setUserScore(0);
        user.setLoadTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        user.setRegisterType(Const.REGISTER_TYPE_SIKU);
        user.setUpdateTime(new Date());

        this.saveUser(user);
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse findUserByUnIonId(String unionId) {
        if (StringUtils.isEmpty(unionId)) {
            throw new NsiOperationException("参数不合法！");
        }
        User currentUser = userMapper.selectByUnionId(unionId);
        if (currentUser == null) {
            throw new NsiOperationException("该用户不存在!");
        }
        return ServerResponse.createBySuccess(currentUser);
    }

    @Override
    public User sysLogin(String username, String password) {
        User user = userMapper.selectByUserName(username);
        return user;
    }

    /**
     * 手机注册功能
     */
    @Override
    public ServerResponse phoneRegister(User user) {
        if (StringUtils.isBlank(user.getUserPortrait())) {
            user.setUserPortrait("0");
        }
//        默认用户等级3
        user.setMemberSign(3);
        user.setLoadTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        user.setUserScore(0);
        user.setUserRegistercode(RandomStringUtils.randomNumeric(6));
        int resultCount = userMapper.insert(user);

        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功-手机注册");
    }

    /**
     * 邮箱激活码验证
     */
    @Override
    public ServerResponse UsermailVerify(String Usermail, String VerifyCode) {
        int resultCount = userMapper.selectByVerifyCode(Usermail, VerifyCode);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败:注册邮件发送异常");
        }
        //注册成功：用户等级设为3
        int Member_sign = 3;
        resultCount = userMapper.updateByUserName(Usermail, Member_sign);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("注册失败：更新用户等级失败");
        }
        //			发送通知邮件
        try {
            String adminEmail = PropertiesUtil.getProperty("admin.email");
            MailUtil.SendNotifyMail(adminEmail, "新用户注册成功:" + Usermail + "-" + VerifyCode + "");
        } catch (Exception e) {
            log.error("【邮箱激活功能异常】msg:{}", e.getMessage());
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }


    /**
     * 登录功能
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse login(String username, String password) {

        //定义数字范围(正则表达式) 手机号登录
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(username);
        if (isNum.matches()) {
            System.out.println("手机登录：" + username);
            User user = userMapper.selectByPhoneAndPwd(username, password);
            if (user == null) {
                return ServerResponse.createByErrorMessage("密码错误");
            }
            user.setPassword(StringUtils.EMPTY);
            int cc = username.length() * user.getMemberSign() + 987789;
            user.setUserRegistercode(String.valueOf(cc));
            return ServerResponse.createBySuccess("登录成功", user);
        }

        int resultCount = userMapper.checkByUserName(username);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        User user = userMapper.selectByNameAndPwd(username, password);
        if (user == null) {
            return ServerResponse.createByErrorMessage("密码错误");
        }
//        判断是否注册过
        if (user.getMemberSign().equals(-1)) {
            return ServerResponse.createByErrorMessage("邮箱未激活，请检查邮箱");
        }

        user.setPassword(StringUtils.EMPTY);

        int cc = username.length() * user.getMemberSign() + 987789;
        user.setUserRegistercode(String.valueOf(cc));
        return ServerResponse.createBySuccess("登录成功", user);

    }


    /**
     * 验证-用户cookie校验
     *
     * @param userName
     * @param member_sign
     * @param UserVerifyCode
     * @return
     */
    @Override
    public ServerResponse verify(String userName, String member_sign, String UserVerifyCode) {
        if (StringUtils.isBlank(userName)) {
            return ServerResponse.createByErrorMessage("验证失败：未登录");
        }
//        简单校验，待更新
//        校验cookie
        int cc = userName.length() * Integer.parseInt(member_sign) + 987789;
        if (cc == Integer.parseInt(UserVerifyCode)) {
            return ServerResponse.createBySuccess("验证成功");
        }
        return ServerResponse.createByErrorMessage("验证失败：UserVerifyCode失效");
    }

    @Override
    public User findUserByWechatId(String wechatId) {
        return userMapper.validByWechatId(wechatId);
    }

    @Override
    public User findByWechatIdAndUnionId(String wechatId, String unionId) {
        return userMapper.validByWechatIdAndUnionId(wechatId, unionId);
    }


    /**
     * 验证用户是否注册过
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse UserMailCheck(String UserMail) {
        int resultCount = userMapper.checkByUserName(UserMail);
        if (resultCount == 0) {
            return ServerResponse.createBySuccess("用户未注册过!");
        }
        return ServerResponse.createByErrorMessage("用户已注册过!");
    }


    /**
     * 获取用户详细信息
     *
     * @param userName
     * @return
     */
    @Override
    public ServerResponse getUserInformation(String userName) {
        User user = userMapper.selectByUserName(userName);
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }


    /**
     * 根据用戶名获取用户信息
     *
     * @param userName
     * @return
     */
    @Override
    public ServerResponse<User> getUserInfo(String userName) {
        if (StringUtils.isBlank(userName)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        User user = userMapper.selectByUserName(userName);
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }

    /**
     * 根据Id修改用户信息
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updateInfomation(User user) {
        int rowCount = userMapper.updateByPrimaryKeySelective(user);
        if (rowCount == 0) {
            return ServerResponse.createByErrorMessage("修改失败");
        }
        return ServerResponse.createBySuccessMessage("修改成功");
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> updateUserInformation(User user) {
        int rowCount = userMapper.updateByPrimaryKeySelective(user);
        if (rowCount == 0) {
            return ServerResponse.createByErrorMessage("修改失败");
        }
        return ServerResponse.createBySuccessMessage("修改成功");
    }

    /**
     * 忘记密码01-发送验证码
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse forgetPW(String UserMail) {

        int resultCount = userMapper.checkByUserName(UserMail);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("邮箱错误！");
        }
        //	邮箱存在
        try {
            //发送忘记密码 验证码
            MailUtil.ForgetPWsendMail(UserMail);
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess("找回密码邮件发送成功！");
    }

    /**
     * 忘记密码02-验证 邮箱激活码
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse forgetPWverify(String UserMail, String Code) {

        int code = Integer.parseInt(Code);
//			1、获取参数
//			2、校验 注意“小时数”需要+1判断
//			3、返回值 原mail ，授权可以改密码
        System.out.println("User_api:忘记密码校验：" + UserMail + "&" + code);
        //基于时间和邮件地址字符长度的加密算法
        Calendar time = Calendar.getInstance();
        System.out.println("ForgetPWsendMail:cc加密算法：hour:" + time.get(Calendar.HOUR_OF_DAY));
        int time_hour = time.get(Calendar.HOUR_OF_DAY);
        int cc = UserMail.length() * time_hour + 987654;
        int cc02 = UserMail.length() * (time_hour + 1) + 987654;
        if (code == cc | code == cc02) {
            return ServerResponse.createBySuccess("验证成功！");
        } else {
            return ServerResponse.createByErrorMessage("验证码错误！");
        }
    }


    /**
     * 修改密码-忘记密码03（通用）
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse PWAlter(String UserMail, String password) {
        int count = userMapper.updateByPassword(UserMail, password);
        if (1 == count) {
            return ServerResponse.createBySuccess("修改成功！");
        } else {
            return ServerResponse.createByErrorMessage("修改失败！错误代码：" + count + "");
        }
    }


    /**
     * 获取微信 OpenId
     *
     * @param code
     * @return
     */
    @Override
    public ServerResponse<String> WechatGetOpenId(String code) {
        String appid = "wxeec22e42c2dd116e";
        String secret = "91f47a41a5f278e47dc4bb521d8fe5a8";
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        //微信扫码实现函数 ：通过code 获取 微信 ID
        String OpenId = Model.WechatHttpRequest(requestUrl, "POST", "");
        return ServerResponse.createBySuccess("获取微信OpenId成功", OpenId);
    }


    /**
     * 微信扫码登录
     *
     * @param OpenId
     * @return
     */
    @Override
    public ServerResponse<User> WechatLogin(String OpenId) {
        User user = userMapper.selectByWechatId(OpenId);
        if (user == null) {
            return ServerResponse.createByErrorMessage("未绑定OpenId");
        }
//        兼容老接口 验证方法
        int UserVerifyCode = user.getUsername().length() * user.getMemberSign() + 987654;
        user.setUserRegistercode(String.valueOf(UserVerifyCode));

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }


    /**
     * 微信用户绑定
     *
     * @param UserName
     * @return
     */
    @Override
    public ServerResponse<String> WechatBinding(String UserName, String Password, String OpenId) {
        User user = userMapper.selectByNameAndPwd(UserName, Password);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户账号密码错误！");
        }
        int rowCount = userMapper.updateByWechatBinding(UserName, OpenId);
        if (rowCount == 0) {
            return ServerResponse.createByErrorMessage("绑定失败");
        }
        return ServerResponse.createBySuccessMessage("绑定成功");
    }


    @Override
    public ServerResponse wechatBindUnionId(String username, String unionId) {
        User user = userMapper.selectByUserName(username);
        if (user == null) {
            throw new NsiOperationException("用户邮箱不正确!");
        }
        user.setUnionId(unionId);
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKey(user);
        return ServerResponse.createBySuccessMessage("绑定成功");
    }


    /**
     * 用户反馈
     *
     * @param UserName
     * @return
     */
    @Override
    public ServerResponse<String> feedback(String UserName, String Content, String Contact) {
        String User_TureName = "undefinedUser";
        if (!"undefinedUser".equals(UserName)) {
            User user = userMapper.selectByUserName(UserName);
            User_TureName = user.getUserTurename();
        }
        Log log = new Log();
        log.setSign("feedback");
        log.setIndex01(User_TureName);
        log.setIndex02(new Date());
        log.setIndex03(Content);
        log.setIndex04(Contact);
        log.setIndex05(User_TureName);
        int rowCount = logMapper.insert(log);
        if (rowCount == 0) {
            return ServerResponse.createByErrorMessage("反馈失败：插入信息失败");
        }
        return ServerResponse.createBySuccessMessage("反馈成功");
    }


    /**
     * 用户增加积分
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse<String> Score(String UserMail, String ScoreNum) {

        int ScoreNum00 = Integer.parseInt(ScoreNum);
        User user = userMapper.selectByUserName(UserMail);
//        原积分+新增积分
        user.setUserScore(user.getUserScore() + ScoreNum00);
        int rowCount = userMapper.updateByPrimaryKeySelective(user);
        if (rowCount == 1) {
            return ServerResponse.createBySuccess("用户积分更新成功");
        }
        return ServerResponse.createByErrorMessage("用户积分更新失败！");
    }


    /**
     * 后台用户搜索
     *
     * @param searchKey
     * @return
     */
    @Override
    public ServerResponse getUserList(String searchKey, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectByAdminSearch(searchKey);
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 删除测试用户
     *
     * @param UserMail
     * @return
     */
    @Override
    public ServerResponse deleteTestUser(String UserMail) {
        userMapper.deleteByUserName(UserMail);
        return ServerResponse.createBySuccess("返回成功");
    }


    @Override
    public void saveMallRegister(User user) {
        User currentUser = new User();
        currentUser.setUsername(user.getUsername());
        currentUser.setPassword("123456");
        currentUser.setUserTurename(user.getUserTurename());
        currentUser.setUserOrganization(user.getUserOrganization());
        currentUser.setWechatid(user.getWechatid());
        currentUser.setMemberSign(3);
        currentUser.setLoadTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        currentUser.setRegisterType("购买课程");

        userMapper.insertSelective(currentUser);
    }

    @Override
    public ServerResponse completionWechatUser(User user) {
        if (user.getUnionId() == null) {
            return ServerResponse.createByErrorCodeMessage(500, "参数不全");
        }
        User newUser = userMapper.selectByUnionId(user.getUnionId());
        user.setId(newUser.getId());
        int i = userMapper.updateByPrimaryKeySelective(user);
        return ServerResponse.createBySuccess("补全信息成功", i);
    }

    @Override
    public User selectByUserMail(String username) {
        return userMapper.selectByUserName(username);
    }

    @Override
    public ServerResponse modifyUserByWechatId(String wechatId, String unionId) {
        User user = userMapper.selectByUnionId(unionId);
        if (user == null) {
            int rowCount = userMapper.updateByWechatId(wechatId, unionId);
            if (rowCount <= 0) {
                return ServerResponse.createByErrorMessage("修改失败");
            } else {
                return ServerResponse.createBySuccess("修改成功");
            }
        } else {
            return ServerResponse.createBySuccess();
        }
    }


    //获取二维码
    @Override
    public ServerResponse getQrcodeStr() {
        String accessToken = this.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String sceneStr = "xinxueshuo.cn" + System.currentTimeMillis();
        String params = "{\"expire_seconds\":604800, \"action_name\":\"QR_STR_SCENE\", \"action_info\":{\"scene\":{\"scene_str\":\"" + sceneStr + "\"}}}";
        String responseStr = null;
        try {
            responseStr = Httpsrequest.httpsRequest(url, "POST", params);
        } catch (Exception e) {
            log.error("第二返回数据失败", e);
            e.printStackTrace();
        }
        if (responseStr != null) {
            Map<String, Object> resultMap = gson.fromJson(responseStr, Map.class);
            responseStr = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + resultMap.get("ticket");
            resultMap.put("qrCode", responseStr);
            resultMap.put("scenStr", sceneStr);
            return ServerResponse.createBySuccess(resultMap);
        } else {
            return ServerResponse.createByErrorMessage("返回数据失败");
        }
    }


    /**
     * @return
     * @throws Exception
     * @Override 获取access_token
     */
    private String getAccessToken() {
        // 微信扫码关注公众号登录参数
        String app_id = "wx37e5ddff7dc5282e";
        String app_secret = "b1650d18615b1de657519091e977e8cd";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app_id + "&secret=" + app_secret;
        String responseStr = null;
        try {
            responseStr = Httpsrequest.httpsRequest(url, "GET", null);
            System.out.println(responseStr);
        } catch (Exception e) {
            log.error("第一次返回数据失败", e);
            e.printStackTrace();
        }
        Map<String, Object> accessTokenMap = gson.fromJson(responseStr, Map.class);
        return accessTokenMap.get("access_token").toString();
    }


    @Override
    public void getCallback(HttpServletRequest request) {
        Map<String, String> callbackMap = this.xmlToMap(request);
        log.info("【微信扫码登陆回调信息】callbackMap:{}" + callbackMap.toString());
        if (callbackMap != null && callbackMap.get("FromUserName").toString() != null) {
            Map<String, Object> wechatUserInfo = this.getUserInfoByOpenid(callbackMap.get("FromUserName"));
            RedisUtils.expireStr(callbackMap.get("EventKey").toString(), wechatUserInfo.toString());
            return;
        }
    }


    //    公众号扫码登录-推送公众号消息
    @Override
    public ServerResponse checkLoginBySceneStr(String sceneStr) {
        String userInfoKey = RedisUtils.searchRedis(sceneStr);
        String userInfoKey02 = RedisUtils.searchRedis("qrscene_" + sceneStr);
        userInfoKey = (userInfoKey != null) ? userInfoKey : userInfoKey02;

        if (userInfoKey != null) {
            Map<String, Object> userInfoMap = this.mapStringToMap(userInfoKey);
            // 如果用户已关注，推送信息
            String openId = (String) userInfoMap.get("openid");
            log.info("【sceneStr:】" + sceneStr);
            log.info("【userInfoMap:】" + userInfoMap.toString());
            log.info("【openId:】" + openId);
            this.sendWechatPublic_msg(openId);
            return ServerResponse.createBySuccess(userInfoMap);
        } else {
            return ServerResponse.createByError();
        }
    }

    //    发送验证短信
    @Override
    public void sendSms(String mobile) {
        String checkCode = RandomStringUtils.randomNumeric(4);
        // 发送用户
        String templateCode = PropertiesUtil.getProperty("sms.template.code");
        smsUtil.sendSms(mobile, templateCode, "{\"code\":\"" + checkCode + "\"}");
        // 存入redis
        RedisUtils.expireSet("SMS_" + mobile, 120000L, checkCode);
    }


    /**
     * 微信公众号扫码登录 openId獲取用戶信息
     *
     * @param openId
     * @return
     */
    private Map<String, Object> getUserInfoByOpenid(String openId) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openId;
        String responseStr = null;
        try {
            responseStr = Httpsrequest.httpsRequest(url, "GET", null);
            System.out.println("openId-用戶信息responseStr:" + responseStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (responseStr != null) {
            Map<String, Object> map = gson.fromJson(responseStr, Map.class);
            return map;
        }
        return null;
    }


    /**
     * 微信公众号扫码登录 获取openId
     *
     * @param openId
     * @return
     */
    @Override
    public Boolean sendWechatPublic_msg(String openId) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        String nowTime = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date());
        String jsonString = "{\n" +
                "\"touser\":\"" + openId + "\",\n" +
                "\"template_id\":\"OHrnU_3XfMSgJ09bJ6scx2ha1O0XajVRc0UT8wknJso\",\n" +
                "\"url\":\"http://data.xinxueshuo.cn\",\n" +
                "\"topcolor\":\"#FF0000\",\n" +
                "\"data\":{\n" +
                "\"first\": {\n" +
                "\"value\":\"您成功登录了新学说网站\",\n" +
                "\"color\":\"#173177\"\n" +
                "},\n" +
                "\"keyword1\":{\n" +
                "\"value\":\"二维码扫码安全登录\",\n" +
                "\"color\":\"#173177\"\n" +
                "},\n" +
                "\"keyword2\":{\n" +
                "\"value\":\"" + nowTime + "\",\n" +
                "\"color\":\"#173177\"\n" +
                "},\n" +
                "\"remark\":{\n" +
                "\"value\":\"如果不是您本人操作，请及时修改个人密码，确保账户安全。\",\n" +
                "\"color\":\"#173177\"\n" +
                "}\n" +
                "}" +
                "}";
        String backMsg = "";
        try {
            backMsg = Httpsrequest.httpsRequest(url, "POST", jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = JSON.parseObject(backMsg);
//        判断是否成功
        if (map.get("errcode").equals("0")) {
            return true;
        } else {
            System.out.println("公众号扫码登录 发送消息失败 backMsg:" + backMsg);
            return false;
        }
    }


    /**
     * xml转为map
     *
     * @param httpServletRequest
     * @return
     */
    private Map<String, String> xmlToMap(HttpServletRequest httpServletRequest) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            InputStream inputStream = httpServletRequest.getInputStream();
            SAXReader reader = new SAXReader(); // 读取输入流
            org.dom4j.Document document = reader.read(inputStream);
            Element root = document.getRootElement(); // 得到xml根元素
            List<Element> elementList = root.elements(); // 得到根元素的所有子节点
            // 遍历所有子节点
            for (Element e : elementList)
                map.put(e.getName(), e.getText());
            // 释放资源
            inputStream.close();
            inputStream = null;
            return map;
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }


    /**
     * 字符串转成Map
     *
     * @param str
     * @return
     */
    private static Map<String, Object> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, Object> map = new HashMap<>();
        for (String newStr : strs) {
            String key = newStr.split("=")[0].trim();
            String value = null;
            if (!newStr.trim().endsWith("=")) {
                value = newStr.split("=")[1].trim();
            } else {
                value = "";
            }
            map.put(key, value);
        }
        return map;
    }


}
